// pages/login/login.js
var app = getApp()
var WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import api from '../../utils/api';
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  onShow() {

  },

  onClickClose() {
    if (app.globalData.scanId != 0 || app.globalData.webUrl != '')  {
      app.globalData.scanId = 0;
      app.globalData.webUrl = '';
      wx.switchTab({
        url: '/pages/index/index'
      });
    } else {
      wx.navigateBack({
        delta: getCurrentPages().length
      })
    }
  },

  //获取用户信息
  getUserInfo(e) {
    Toast.loading({ message: '登录中...', forbidClick: true });
    let login = wx.getStorageSync('login');
    wx.getUserProfile({
      desc: '授权完善公开信息,获得更好体验',
      success: res => {
        let userInfo = res.userInfo;
        api.setWxUserInfo({
          "openId": login.openid,
          "unionId": login.unionId,
          "mobile": login.phoneNumber,
          "nickName": userInfo.nickName,
          "avatarUrl": userInfo.avatarUrl,
          "gender": userInfo.gender,
          "country": userInfo.country,
          "province": userInfo.province,
          "city": userInfo.city,
          "language": userInfo.language
        }).then((res) => {
          if (res.data.code != 0) return;
          wx.setStorageSync('userInfo', userInfo);
          wx.setStorageSync('userId', res.data.msg);
          Toast.success('登录成功');
          if (app.globalData.scanId != 0) {
            api.getNewsInfoById({ "newsId": app.globalData.scanId }).then(newsInfo => {
              if (newsInfo.data.code == 0) {
                if (newsInfo.data.data[0].newsUrl) {
                  let openid = newsInfo.data.data[0].newsUrl.indexOf('?') != -1 ? '&openid=' : '?openid=';
                  let url = newsInfo.data.data[0].newsUrl + openid + res.data.msg;
                  wx.redirectTo({
                    url: '/pages/web/web?url=' + encodeURIComponent(url),
                  })
                }
                else {
                  wx.switchTab({
                    url: '/pages/index/index'
                  });
                }
              } else {
                wx.switchTab({
                  url: '/pages/index/index'
                });
              }
            })
          }
          else if(app.globalData.webUrl!=''){
            wx.redirectTo({
              url: '/pages/web/web?shareurl=' + encodeURIComponent(app.globalData.webUrl),
            })
          }
          else {
            wx.navigateBack({
              delta: getCurrentPages().length
            })
          }
        })
      }
    })
  },
})